<script setup lang="ts">
import { ref, onMounted, nextTick, watch } from "vue";
import { useECharts } from "@pureadmin/utils";

const props = defineProps<{
  data: any;
}>();

const chartRef = ref<HTMLDivElement>();
const { setOptions, resize, getInstance } = useECharts(chartRef);

const drawChart = () => {
  const chartData = [
    {
      value: props.data.high?.count || 0,
      name: "高风险",
      itemStyle: { color: "#f5222d" },
    },
    {
      value: props.data.medium?.count || 0,
      name: "中风险",
      itemStyle: { color: "#fa8c16" },
    },
    {
      value: props.data.low?.count || 0,
      name: "低风险",
      itemStyle: { color: "#faad14" },
    },
    {
      value: props.data.safe?.count || 0,
      name: "安全",
      itemStyle: { color: "#52c41a" },
    },
  ];

  setOptions({
    tooltip: {
      trigger: "item",
      formatter: "{b}: {c} ({d}%)",
    },
    legend: {
      bottom: 10,
      left: "center",
    },
    series: [
      {
        name: "风险等级",
        type: "pie",
        radius: "50%",
        data: chartData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
      },
    ],
  });
};

onMounted(() => {
  nextTick(() => {
    drawChart();
    // 延迟调用 resize，确保图表已初始化
    setTimeout(() => {
      if (getInstance()) {
        resize();
      }
    }, 100);
  });
});

watch(() => props.data, drawChart, { deep: true });

defineExpose({ resize });
</script>

<template>
  <el-card shadow="hover">
    <template #header>
      <span class="card-title">风险等级分布</span>
    </template>
    <div ref="chartRef" style="height: 300px"></div>
  </el-card>
</template>

<style lang="scss" scoped>
.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}
</style>
